package admin.controllers;

import helpers.EmailHelper;
import helpers.IdUniqueHelper;
import helpers.UrlHelper;
import helpers.ValidateHelper;

import java.io.IOException;
import java.net.URLDecoder;
import java.util.List;
import java.util.TreeMap;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import search.ArticleSearchEngine;
import systems.ConfigSystem;
import systems.Recently;
import systems.RecentlyTag;

import admin.forms.ArticleForm;
import admin.models.ArticleModel;
import admin.models.CategoryModel;
import admin.models.UserModel;

import entities.Article;
import entities.ArticleSearch;
import entities.Category;
import entities.SiteConfig;
import entities.User;

@SuppressWarnings("serial")
public class ArticleEditServlet extends HttpServlet {
	public void doGet(HttpServletRequest request, HttpServletResponse response)
		throws IOException, ServletException {
		TreeMap<String, String> check = new TreeMap<String, String>();
		
		String path = ((HttpServletRequest) request).getRequestURI();
		String id = URLDecoder.decode(path.replaceAll(request.getServletPath() + "/", ""),"UTF-8");
		
		if (id == null || id.isEmpty()) {
			response.sendRedirect("/admin/article/list");
			return ;
		}
		
		ArticleModel articleModel = ArticleModel.getInstance();
		Article article = articleModel.getArticle(id);
		
		if (article == null) {
			response.sendRedirect("/admin/article/list/" + id);
			return ;
		}
		
		
		CategoryModel categoryModel = CategoryModel.getInstance();
		List<Category> categories = (List<Category>) categoryModel.getAll();
		
		request.setAttribute("form", "edit");
		request.setAttribute("check", check);
		request.setAttribute("article", article);
		request.setAttribute("categories", categories);
		try {
			request.getRequestDispatcher("/admin/pages/article_form.jsp").forward(request, response);
		} catch (ServletException e) {
			e.printStackTrace();
		}
	}
	
	public void doPost(HttpServletRequest request, HttpServletResponse response)
		throws IOException, ServletException {
		
		SiteConfig siteConfig = ConfigSystem.getConfigs();
		TreeMap<String, String> check = new TreeMap<String, String>();
		
		String path = ((HttpServletRequest) request).getRequestURI();
		String id = URLDecoder.decode(path.replaceAll(request.getServletPath() + "/", ""),"UTF-8");
		
		if (id == null || id.isEmpty()) {
			response.sendRedirect("/admin/article/list");
			return ;
		}
		
		ArticleModel articleModel = ArticleModel.getInstance();
		Article article = articleModel.getArticle(id);
		
		if (article == null) {
			response.sendRedirect("/admin/article/list");
			return ;
		}
		
		
		CategoryModel categoryModel = CategoryModel.getInstance();
		List<Category> categories = (List<Category>) categoryModel.getAll();
		
		TreeMap<String, Object> form = ArticleForm.checkValid(request, article);
		article = (Article) form.get("article");
		check = (TreeMap<String, String>) form.get("checkValid");
		
		if (check.size() == 0) {
			articleModel.insert(article);
			
			request.setAttribute("success", "Update article " + id + " success");
			
			//Update recently Cache
			if (article.getStatus() == 1) {
				Recently.update(article);
				//Update tag
				RecentlyTag.insert(article.getKeywords());
			} else {
				Recently.remove(article);
			}
			
			/***** SEND MAIL *****/
			if (siteConfig.getSubmitStatus() == 2 && article.getStatus() == 1) {
				String fromEmail = siteConfig.getContactEmail();
				String toEmail = article.getEmail();
				
				String serverUrl = UrlHelper.getServerUrl(request);
				String serverName = UrlHelper.getDomainServer(request);
				String strUrl = serverUrl + "/email-publish-article?id="+article.getId()+"&key=" + article.getAuthKey();
				String strSubject = "Publish Article with id " + article.getId();
				
				if (toEmail.isEmpty() && !article.getCreator().isEmpty()) {
					UserModel userModel = UserModel.getInstance();
					User author = userModel.getUser(article.getCreator());
					if (author != null) {
						toEmail = author.getUsername();
					}
				}
				
				if(!toEmail.isEmpty() && ValidateHelper.isEmail(toEmail)) {
					System.out.println(strUrl + " from " + fromEmail + " -> to " + toEmail);
					EmailHelper.sendMailFromUrl(serverName + " <" + fromEmail + ">", strSubject, strUrl, toEmail);
				}
			} 
			/***** END SEND MAIL *****/
		}
		
		request.setAttribute("form", "edit");
		request.setAttribute("check", check);
		request.setAttribute("article", article);
		request.setAttribute("categories", categories);
		try {
			request.getRequestDispatcher("/admin/pages/article_form.jsp").forward(request, response);
		} catch (ServletException e) {
			e.printStackTrace();
		}
	}
}
